<script setup lang="ts">
  import {
    SITE_NAME,
    TOKEN_NAME,
    USER_INFO
  } from '~/common/constants'
  import {isEmail} from '~/utils/regex'
  import { setCookie } from '~/utils/cookie'
  import {serialize} from '~/utils/parse'
  import {getLocalUserInfo} from '~/utils/localUserInfo'
  /**
   * 注册相关表单和页面显示数据
   */
  const nuxtApp = useNuxtApp()
  const showRegister = ref(false)
  const registerForm = ref(null)
  const sendEmailRequestLoading = ref(false)
  const registerFormData = ref({
    email: null
  })

  /**
   * 字段校验规则定义
   */
  function validateEmail(rule, value) {
    return isEmail(value)
  }
  const registerRules = {
    email: [
      {
        required: true,
        message: '请输入邮箱'
      },
      {
        validator: validateEmail,
        message: '邮箱格式不正确',
        trigger: 'blur'
      }
    ]
  }

  /**
   * 弹出注册弹窗要求输入邮箱进行注册
   */
  const openRegisterModal = () => {
    showRegister.value = true
  }

  /**
   * 发送账号注册邮件到输入邮箱内
   */
  const sendEmailForRegister = async () => {
    sendEmailRequestLoading.value = true
    try {
      const {msg} = await nuxtApp.$request('/register', {
        method: 'POST',
        body: {
          type: 0,
          email: registerFormData.value.email
        },
        key: 'sendRegisterEmail'
      })
      // 发送注册邮件成功
      nuxtApp.$mutual.message.success(msg, {
        onAfterLeave: () => showRegister.value = false
      })
    } catch (e) {
    } finally {
      sendEmailRequestLoading.value = false
    }
  }

  /**
   * 登录相关表单和页面显示数据
   */
  const loginForm =ref(null)
  const showLogin = ref(false)
  const accountLogin = ref(false)
  const loginFormData = ref({
    username: null,
    password: null
  })

  const loginRules = {
    username: [
      {
        required: true,
        message: '请输入账号/邮箱/手机号'
      }
    ],
    password: [
      {
        required: true,
        message: '请输入密码'
      }
    ]
  }

  const handleLogin = async () => {
    showLogin.value = true
  }

  const userInfo = useUserInfo()
  /**
   * 发送登录请求
   */
  const login = () => {
    accountLogin.value = true
    loginForm.value?.validate(async (errors) => {
      if (errors) {
        accountLogin.value = false
        return
      }
      try {
        const {msg, data} = await nuxtApp.$request('/login', {
          method: 'POST',
          body: loginFormData.value,
          server: false,
          key: 'login'
        })
        // 登录成功后保存令牌到cookie中
        const tokenCookie = setCookie(TOKEN_NAME)
        tokenCookie.value = data.tokenValue
        // 登录成功后保存用户信息到localStorage中
        localStorage.setItem(USER_INFO, serialize(data.userInfo))

        // useNuxtApp().$useUserInfo.value = data.userInfo
        userInfo.value = data.userInfo
        useLoginStatus().value = true

        nuxtApp.$mutual.message.success(msg, {
          onAfterLeave: () => {
            showLogin.value = false
            navigateTo('/')
          }
        })
      } catch (e) {
      }
      finally {
        accountLogin.value = false
      }
    })
  }
  const showPopover = ref(false)
</script>
<template>
  <ClientOnly>
    <div class="login-button-wrap">
      <NButtonGroup v-if="!userInfo" size="medium" class="login-btn">
        <NButton class="login" type="default" @click="handleLogin">
          登录
        </NButton>
        <NButton class="register" type="default" @click="openRegisterModal">
          注册
        </NButton>
        <!--                      <ClientOnly><LangSwitcher></LangSwitcher></ClientOnly>-->
      </NButtonGroup>
      <n-popover
        v-else
        :show="showPopover"
        placement="bottom"
        trigger="manual"
      >
        <template #trigger>
          <n-avatar round @click="showPopover = !showPopover">
            {{userInfo.nickname}}
          </n-avatar>
        </template>
        <NuxtLink :to="`/user/${userInfo.accountId}`"><span>我的主页</span></NuxtLink>
      </n-popover>
    </div>
    <!-- 注册弹窗 start -->
    <NModal
      v-model:show="showRegister"
      preset="card"
      :title="`加入${SITE_NAME}`"
      :style="{
      width: '650px'
    }"
      :bordered="false"
    >
      <NForm :rules="registerRules" :model="registerFormData" ref="registerForm">
        <NFormItem path="email">
          <NInput v-model:value="registerFormData.email" type="text" placeholder="请输入您的邮箱" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NButton :loading="sendEmailRequestLoading" @click="sendEmailForRegister">注册</NButton>
      </template>
    </NModal>
    <!-- 注册弹窗 end -->
    <!-- 登录弹窗 start -->
    <NModal
      v-model:show="showLogin"
      preset="card"
      :title="`登录${SITE_NAME}浏览更多有趣内容`"
      :style="{
      width: '650px'
    }"
      :bordered="false"
    >
      <NTabs
        class="card-tabs"
        default-value="accountLogin"
        size="large"
        animated
        pane-wrapper-style="margin: 0 -4px"
        pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;"
      >
        <NTabPane name="accountLogin" tab="账号登录">
          <NForm :rules="loginRules" :model="loginFormData" ref="loginForm">
            <NFormItem path="username">
              <NInput
                v-model:value="loginFormData.username"
                placeholder="账号/邮箱/手机号"/>
            </NFormItem>
            <NFormItem path="password">
              <NInput type="password"
                      v-model:value="loginFormData.password"
                      placeholder="密码"/>
            </NFormItem>
          </NForm>
          <NButton type="primary" block secondary strong :loading="accountLogin" @click="login">
            登录
          </NButton>
        </NTabPane>
        <!--      <NTabPane name="phoneLogin" tab="验证码登录">-->
        <!--        <NForm>-->
        <!--          <NFormItemRow label="手机号">-->
        <!--            <n-input />-->
        <!--          </NFormItemRow>-->
        <!--          <n-form-item-row label="密码">-->
        <!--            <n-input />-->
        <!--          </n-form-item-row>-->
        <!--        </NForm>-->
        <!--        <n-button type="primary" block secondary strong>-->
        <!--          注册-->
        <!--        </n-button>-->
        <!--      </NTabPane>-->
      </NTabs>
    </NModal>
    <!-- 登录弹窗 end -->
  </ClientOnly>
</template>
<style scoped lang="ts">

</style>
